package tuling.netty.codec;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

/**
 * @author RenGaoshuai
 * @date 2023/12/4 10:23
 * @description
 */
public class CodecServer {

    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //获取通道
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //设置编解码器，netty自带的String类型编解码器
//                            pipeline.addLast("stringencode",new StringEncoder());
//                            pipeline.addLast("stringdecode",new StringDecoder());
//                            //对象类型,注意传输的对象必须实现序列化接口，这是使用的java的序列化，速度较慢
                            pipeline.addLast("objectencode", new ObjectEncoder());
                            pipeline.addLast("objectdecode", new ObjectDecoder(ClassResolvers.cacheDisabled(null)));

                            pipeline.addLast(new CodecServerHandler());
                        }
                    });
            ChannelFuture cf = bootstrap.bind(9000).sync();
            System.out.println("server start success");

            //对通道关闭监听，这里的sync()方法作用同上
            cf.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("server interrupted exception");
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
